"""
Experimento 1: Escaneo a Ministerios y Comparacion de tiempos

Dada la lista de los ministerios nacionales son sus respectivos
dominios y direcciones ip, se pretende hacer un escaneo
no intrusivo (syn scan) de sus puertos.

Se miden tiempos de ejecucion de "connect scan" y "syn scan"
para algunos host arbitrarios.
Se genera un promedio de los tiempos de cada tipo de scan

Se va a guardar, por un lado, la lista de los puertos abiertos
de cada ministerior (mismos datos de la entrada salvo el nombre
y agregando la lista de puertos abiertos y filtrados)
y por otro lado un listado de
puertos abiertos junto a las cantidades detectadas.
"""

from time import time
from scanner import syn_scan, connect_scan

def update(port = None):
  if port != None:
    print ".", port
  else:
    print "."
  
def agregar(dicc, lista):
  for e in lista:
    if e in dicc:
      dicc[e] += 1
    else:
      dicc[e] = 1

f_in     = open("../experimentos/ministerios.in")
f_out    = open("../experimentos/ministerios.out", "w")
f_open   = open("../experimentos/ministerios.open", "w")
f_filter = open("../experimentos/ministerios.filter", "w")
f_time   = open("../experimentos/ministerios.time", "w")

open_ports = []
filtered = []
t_syn = []
t_con = []
abiertos = {}
filtrados = {}

# headers
f_out.write("ns ip open_ports\n")
f_open.write("port cant\n")
f_filter.write("port cant\n")
f_time.write("ns ip syn_time connect_time\n")

for line in f_in:
  l = line.split("|");
  ns = l[1]
  ip = l[2]
  
  print "\nSTARTING", ns, ip
  
  # syn
  print "-- syn scan"
  ts0 = time()
  (open_ports, filtered) = syn_scan(ip, update)
  ts1 = time()
  
  # convert to string: sino write() chilla
  open_ports = [str(i) for i in open_ports]
  filtered = [str(i) for i in filtered]
  
  # connect: without save ports
  print "-- connect scan"
  tc0 = time()
  connect_scan(ip, update)
  tc1 = time()
  
  # add times to lists
  t_syn.append(ts1 - ts0)
  t_con.append(tc1 - tc0)
    
  # save mins data
  m_open = ",".join(open_ports)
  m_filter = ",".join(filtered)
  f_out.write(ns + " " + ip + " " + m_open + " " + "\n")
  f_time.write(ns + " " + ip + " " + str(ts1-ts0) + " " + str(tc1-tc0) + "\n")
  
  # add to dicts
  agregar(abiertos, open_ports)
  agregar(filtrados, filtered)

# save open ports
for k, v in abiertos.iteritems():
  f_open.write(str(k) + " " + str(v) + "\n")

# save filtered ports
for k, v in filtrados.iteritems():
  f_filter.write(str(k) + " " + str(v) + "\n")

# promedios
prom_syn = '%.3f' %(sum(t_syn) / float(len(t_syn)))
prom_con = '%.3f' %(sum(t_con) / float(len(t_con)))
print "syn prom:", prom_syn, "seg"
print "con prom:", prom_con, "seg"

# close
f_out.close()
f_open.close()
f_filter.close()
f_time.close()
